package com.moben.local.script.boss.edge;

import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.edge.EdgeOptions;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.util.List;
import java.util.*;

public class BossByEdgeFrame_v2 {
    public static final Map<String, String> SALARY_MAP = new HashMap<>();
    static {
        SALARY_MAP.put("\uE031", "0");
        SALARY_MAP.put("\uE032", "1");
        SALARY_MAP.put("\uE033", "2");
        SALARY_MAP.put("\uE034", "3");
        SALARY_MAP.put("\uE035", "4");
        SALARY_MAP.put("\uE036", "5");
        SALARY_MAP.put("\uE037", "6");
        SALARY_MAP.put("\uE038", "7");
        SALARY_MAP.put("\uE039", "8");
        SALARY_MAP.put("\uE040", "9");
        SALARY_MAP.put("\uE03A", "9");
    }

    public static void main(String[] args) throws InterruptedException {
        // 配置文件读取
        List<String> listCompany = new ArrayList<>(); // 排除公司
        String driverPath = "";// 驱动路径
        String userTempDir = "";// 浏览器储存用户信息路径
        // 寻找exe文件同位置的配置文件
        // File file = new File(System.getProperty("user.dir").replaceAll("WebStart", "") + "/moben.properties");
        File file = new File("moben-local/moben.properties"); // 项目路径中的配置文件
        try(FileInputStream fileInputStream = new FileInputStream(file)){
            Properties properties = new Properties();
            properties.load(new InputStreamReader(fileInputStream, "UTF-8"));
            driverPath = properties.getProperty("driver", "");
            userTempDir = properties.getProperty("userdir", "");
            String property = properties.getProperty("exclude.company", "");
            if (StringUtils.isNotBlank(property)){
                listCompany = Arrays.asList(property.split(","));
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 岗位 和驱动 路径
        UIManager.put("Label.font", new Font("宋体", Font.PLAIN, 16));
        UIManager.put("Button.font", new Font("宋体", Font.BOLD, 16));
        UIManager.put("TextField.font", new Font("宋体", Font.PLAIN, 16));
        JFrame frame = new JFrame();
        frame.setSize(450,250);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout(FlowLayout.LEFT));
        frame.setLocationRelativeTo(null);
        JLabel label = new JLabel("岗位：");
        JTextField textField = new JTextField("中级java 开发",20);
        JLabel labelSalary = new JLabel("可接受最低薪资：");
        JTextField acceptSalary = new JTextField("12",20);


        JButton button = new JButton("开始");

        JTextField textField1 = new JTextField(driverPath,20);
        String driverText = textField1.getText();
        JLabel labelBlank = new JLabel("                                                ");
        JLabel label2 = new JLabel("请先登录");
        JButton jButton = new JButton("继续");

        // boss step1
        // EdgeOptions edgeOptions = new EdgeOptions();
        System.setProperty("webdriver.edge.driver", driverText);
        EdgeOptions edgeOptions = new EdgeOptions();
        // 启用特定功能
        Map<String, Object> edgeOptionArg = new HashMap<>();
        ArrayList<String> strings = new ArrayList<>();
        // 无头模式 即 要不要打开浏览器窗口
        // strings.add("--headless=off");
        // strings.add("--no-sandbox");
        // strings.add("--disable-dev-shm-usage");
        // strings.add("--disable-gpu");
        strings.add("--remote-debugging-port=9222");
        // strings.add("--single-process");
        // strings.add("--start-maximized");
        // strings.add("--disable-extensions");
        strings.add("detach=True");
        // strings.add("profile-directory=Default");
        // strings.add("user-data-dir=C:\\Users\\moben\\AppData\\Local\\Microsoft\\Edge\\User Data");
        strings.add("profile-directory=Profile 1");
        // strings.add("user-data-dir=D:\\software\\select\\edge\\temp\\Profile 1");
        strings.add("user-data-dir=" + userTempDir + "\\Profile 1");
        strings.add("--disable-blink-features=AutomationControlled");
        strings.add("useAutomationExtension=false");
        edgeOptionArg.put("args", strings);
        edgeOptions.setCapability("ms:edgeOptions", edgeOptionArg);
        // 记录会话
        EdgeDriver edgeDriver = new EdgeDriver(edgeOptions);
        // EdgeDriver edgeDriver = new EdgeDriver();
        System.out.println("edge sessionId"+edgeDriver.getSessionId());

        if (StringUtils.isBlank(driverText)){
            new DriverDialog();
            return;
        }
        edgeDriver.get("https://www.zhipin.com/shanghai/?ka=header-home");
        String windowHandle1 = edgeDriver.getWindowHandle();
        WebDriverWait webDriverWait = new WebDriverWait(edgeDriver, 10);

        List<String> finalListCompany = listCompany;
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String jobText = textField.getText();
                    String salaryText = acceptSalary.getText();
                    step1(edgeDriver, finalListCompany,jobText,Integer.parseInt(salaryText));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    jButton.setEnabled(true);
                }
            }
        });

        jButton.addActionListener(e -> {
            jButton.setEnabled(false);
            thread.start();
        });
        jButton.setEnabled(true);

        frame.add(label);
        frame.add(textField);
        frame.add(new JLabel("                  "));
        frame.add(labelSalary);
        frame.add(acceptSalary);
        // frame.add(button);
        frame.add(labelBlank);
        frame.add(label2);
        frame.add(jButton);
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                thread.interrupt();// 关闭浏览器
                edgeDriver.quit();
            }
        });
        frame.setVisible(true);
    }

    public static void step1(EdgeDriver edgeDriver,List<String> companyList,String jobName,Integer acceptSalary) throws InterruptedException {

        /**
         * 获取职位
         */
        // int s  = (int)Math.ceil(Math.random() * 7) * 100 + 200;
        // Thread.sleep(s + 2000);
        WebDriverWait webDriverWait2 = new WebDriverWait(edgeDriver, 10);
        // 重新获取页面元素
        int num = 0;
        int pageNum = 1;
        while (num <= 100){

            try {
                // System.out.println(edgeDriver.getPageSource());
                // 职位列表
                List<WebElement> jobCards = edgeDriver.findElementsByClassName("card-area");
                for (WebElement jobCard : jobCards) {
                    WebElement jobCompany = jobCard.findElement(By.className("boss-name"));
                    WebElement jobName1 = jobCard.findElement(By.className("job-name"));
                    WebElement jobSalary = jobCard.findElement(By.className("job-salary"));
                    String text = jobSalary.getText();
                    String[] split = text.split("-");
                    String s = split[0];
                    for (Map.Entry<String, String> entry:SALARY_MAP.entrySet()){
                        s = s.replaceAll(entry.getKey(),entry.getValue());
                    }
                    // System.out.println(Integer.parseInt(s)>10);

                    boolean tempJob = jobName1.getText().contains("短期");
                    // 排除外包公司 排除短期项目 排除最小工资<xxx的

                    if (!companyList.contains(jobCompany.getText()) && !tempJob && Integer.parseInt(s)>=acceptSalary){
                        // 点击当前卡片 显示岗位详细信息
                        Thread.sleep(2000 + getRandomNum());
                        try {
                            jobCard.click();
                            Thread.sleep(500 + getRandomNum());
                            new WebDriverWait(edgeDriver, 10);
                            // 获取立即沟通按钮 并点击沟通
                            edgeDriver.findElementByClassName("op-btn-chat").click();
                            Thread.sleep(1000 + getRandomNum());
                            // 点击留在此页面
                            edgeDriver.findElementByClassName("cancel-btn").click();
                        }catch (Exception e){

                        }
                        Thread.sleep(1000 + getRandomNum());
                        num ++;
                    }

                }
                // 重新输入岗位 刷新职位列表
                WebElement searchDiv = edgeDriver.findElementByClassName("c-search-input");
                WebElement searchInput = searchDiv.findElement(By.className("input"));
                searchInput.clear();
                searchInput.sendKeys(jobName);
                try {
                    edgeDriver.findElementByClassName("search-btn").click();
                }catch (Exception e){
                    // System.out.println(e.getMessage());
                }
                int s1  = (int)Math.ceil(Math.random() * 7) * 100 + 200;
                Thread.sleep(s1 + 7000);
            }catch(Exception e){
                System.out.println(e.getMessage());
            }

        }

        System.out.println("今天投递简历的数量：" + num);
        if (num>99){
            edgeDriver.quit();
        }
    }

    public static int getRandomNum() {
        return (int)Math.ceil(Math.random() * 7) * 100 + 200;
    }
}

